<template>
  <a-modal
    v-model:visible="visible"
    :footer="null"
    :title="$t('other.processAdd')"
    width="90%"
    wrap-class-name="large-modal"
    :maskClosable="false"
    :confirm-loading="loading"
    :keyboard="false"
  >
    <a-spin :spinning="loading">
      <div class="make-process-modal-container">
        <aside>
          <a-row class="moinfo-box pb-20">
            <a-col :span="24" class="mb-8">
              <span>{{ $t("hangManage.makeNo") }}：</span>
              <span>{{ moInfo.moNo }}</span>
            </a-col>
            <a-col :span="24" class="mb-8">
              <span>{{ $t("basicData.styleNo") }}：</span>
              <span>{{ moInfo.styleNo }}</span>
            </a-col>
            <a-col :span="24">
              <span>{{ $t("basicData.styleNa") }}：</span>
              <span>{{ moInfo.styleName }} </span>
            </a-col>
          </a-row>
          <div class="version-box">
            <a-form :model="formState" ref="formRef" layout="vertical">
              <a-form-item
                :label="`${$t('basicData.processVerName')}:`"
                :rules="processFormRule.name"
                name="name"
              >
                <a-input
                  v-model:value.trim="formState.name"
                  :maxLength="19"
                  :placeholder="$t('common.pleaseInput')"
                />
              </a-form-item>
              <a-form-item
                :label="`${$t('common.effectDate')}:`"
                name="effectiveDate"
                :rules="processFormRule.effectiveDate"
              >
                <a-date-picker
                  v-model:value="formState.effectiveDate"
                  class="full-width"
                  value-format="YYYY-MM-DD"
                />
              </a-form-item>
              <a-form-item
                :label="`${$t('basicData.totalTime')}:`"
                name="totalTime"
              >
                <a-input-number
                  v-model:value="formState.totalTime"
                  disabled
                  class="full-width"
                >
                  <template #addonAfter> {{ $t("common.seconds") }} </template>
                </a-input-number>
              </a-form-item>
              <a-form-item
                :label="`${$t('basicData.totalPrice')}:`"
                name="totalWages"
              >
                <a-input-number
                  v-model:value="formState.totalWages"
                  disabled
                  class="full-width"
                >
                  <template #addonAfter> {{ $t('other.yuan') }} </template>
                </a-input-number>
              </a-form-item>
            </a-form>
          </div>
        </aside>
        <section>
          <ModalProcessList
            ref="processListRef"
            :styleId="moInfo.styleId"
            :loading="listLoading"
            :tableData="tableData"
            @workTimeChange="workTimeChange"
            @priceChange="priceChange"
            :processVersionId="processVersionId"
            :moId="moId"
          />
        </section>
      </div>
      <div class="modal-operate-btn">
        <a-button class="cancel" @click="onCancel">{{
          $t("common.cancel")
        }}</a-button>
        <a-button type="primary" class="confirm" @click="onConfirm">{{
          $t("common.ok")
        }}</a-button>
      </div>
    </a-spin>
  </a-modal>
</template>
<script setup>
import { ref } from "vue";
import { processFormRule, addList } from "./processConfig";
import ModalProcessList from "./modalProcessList.vue";
import { message } from "ant-design-vue";
import axios from "@/utils/request";
import { cloneDeep, uniqBy } from "lodash";
import moment from "moment";
import i18n from "@/locales/index";
const { t } = i18n.global;
const emits = defineEmits(["ok"]);
let loading = ref(false);
let visible = ref(false);
let listLoading = ref(false);
let moId = ref(); // 制单id
let moInfo = ref({});
let processVersionId = ref();
let processListRef = ref();
let tableData = ref([]);
const formState = ref({});
let formRef = ref();
const open = async (record) => {
  visible.value = true;
  loading.value = true;
  try {
    moId.value = record.moId;
    await getMakeInfo(moId.value);
    initPage();
    loading.value = false;
  } catch {
    loading.value = false;
  }
};
const getMakeInfo = async (id) => {
  // 制单信息
  try {
    const res = await axios.getAction("/api/mo/mo/get", { id });
    moInfo.value = res.data || {};
  } catch {
    message.warning(t("components.getDataErrorPleaseHolder"));
    moInfo.value = {};
  }
};
const initPage = () => {
  tableData.value = cloneDeep(addList);
  processVersionId.value = undefined;
  formState.value = {
    name: null,
    effectiveDate: moment(moment(new Date()).valueOf()).format("YYYY-MM-DD"),
    totalTime: 0,
    totalWages: 0
  }
  // console.log('formState.value', formState.value);
}
const workTimeChange = () => {
  formState.value.totalTime = processListRef.value.dataSource
    .reduce((prev, next) => {
      return prev + (next.standardSeconds || 0);
    }, 0)
    .toFixed(8);
};
const priceChange = () => {
  formState.value.totalWages = processListRef.value.dataSource
    .reduce((prev, next) => {
      return prev + (next.labourCost || 0);
    }, 0)
    .toFixed(8);
};
const queryParams = () => {
  let list = cloneDeep(processListRef.value.dataSource)
  list.forEach(i => {
    i.moId = moId.value
    i.status = i.status   ? 1 : 0
  })
  let { name, effectiveDate } = formState.value
  let params = {
    effectiveDate: moment(effectiveDate).valueOf(),
    name,
    moId: moId.value,
    moProcDetailVOList: list,
  };
  return params;
};
const onCancel = () => {
  visible.value = false;
};
const onConfirm = async () => {
  try {
    await formRef.value.validateFields();
    await processListRef.value.listFormRef.validateFields();
    let list = processListRef.value.dataSource;
    if (list.some((i) => i.section != t("components.dg"))) {
      message.warning(t('other.sectionOnlySelectHang'));
      return;
    }
    //  唯一值校验
    let isUniq = [ 'processNo', 'name', 'processCode'].some(i => uniqBy(list, i).length != list.length)
    if (isUniq) {
      message.warning('工序号，工序名称，工序代码不唯一!!!!!!!!!')
      return
    }
    loading.value = true;
    await sendInfo();
    loading.value = false;
  } catch {
    loading.value = false;
  }
};
const sendInfo = async () => {
  loading.value = true;
  let params = queryParams();
  const res = await axios.postAction("/api/mo/mo-proc/save", params);
  if (res.success) {
    message.success(res.msg || t("common.doSuccess"));
    emits("ok");
    visible.value = false;
  }
};
defineExpose({
  open,
});
</script>
